package com.wangbo.box.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
 * 享元模式  例如连接池
 *
 * 运用共享技术来有効地支持大量细粒度对象的复用。
 */
public class FlyweightPattern {

    static class FlyweightFactory{
        Map<String, Subject> flyweigts = new HashMap<>();

        public Subject getFlyweigts(String key) {
            Subject subject = flyweigts.get(key);
            if (subject == null){
                subject = new SubjectA(key);
                flyweigts.putIfAbsent(key, subject);
            }else {
                System.out.println(key + "已存在");
            }
            return subject;
        }
    }

    interface Subject{
        void show(SubjectExt ext);
    }

    static class SubjectExt{
        private String info;

        public SubjectExt(String info) {
            this.info = info;
        }

        public String getInfo() {
            return info;
        }

        public void setInfo(String info) {
            this.info = info;
        }
    }

    static class SubjectA implements Subject{

        private String key;

        public SubjectA(String key) {
            this.key = key;
            System.out.println(key + "被创建");
        }

        @Override
        public void show(SubjectExt ext) {
            System.out.println(key + ":" + ext.getInfo());
        }
    }

    public static void main(String[] args) {
        FlyweightFactory flyweightFactory = new FlyweightFactory();
        Subject s1 = flyweightFactory.getFlyweigts("a");
        Subject s2 = flyweightFactory.getFlyweigts("a");
        Subject s3 = flyweightFactory.getFlyweigts("a");
        flyweightFactory.getFlyweigts("b");
        flyweightFactory.getFlyweigts("b");
        flyweightFactory.getFlyweigts("c");
        s1.show(new SubjectExt("s1Ext"));
        s2.show(new SubjectExt("s2Ext"));
        s3.show(new SubjectExt("s3Ext"));
    }
}
